from django.core.urlresolvers import reverse
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render


# Create your views here.
def logout_view(request):
    '''注销操作'''
    logout(request)
    return HttpResponseRedirect(reverse('learning_logs:index'))

def register(request):
    '''注册用户'''
    if request.method != "POST":
        form = UserCreationForm()
    else:
        # 处理填好的注册信息
        form = UserCreationForm(request.POST)

        if form.is_valid():
            new_user = form.save()
            # 让用户自动登录, 在重定向到主页
            authenticate_user = authenticate(
                username = new_user.username,
                password = request.POST['password1'])
            login(request, authenticate_user)
            return HttpResponseRedirect(reverse('learning_logs:index'))
    context = {'form' : form}
    return render(request, 'users/register.html', context)